package com.liang.serviceribbon;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author liangyehao
 * @version 1.0
 * @date 2021/3/17 22:09
 * @content
 */
@SpringBootApplication
@RestController
@EnableHystrix
public class RibbonApp {
    public static void main(String[] args) {
        SpringApplication.run(RibbonApp.class,args);
    }

    @Value("${service.name:SERVICE-HI}")
    String serviceName;

    @RequestMapping("/triggerRibbon/hi")
    @HystrixCommand(fallbackMethod = "hiErr")
    public String hi(@RequestParam("name") String name){
        return restTemplate().getForObject("http://"+serviceName+"/hi?name="+name,String.class);
    }

    public String hiErr(String name){
        return "ribbon熔断：Sorry,"+name+". Hystrix,please try again...";
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
